#coding:utf-8
import sys,io,re,os,time,threading,thread
import subprocess
from day_log import log_set
#git pull .if has new,reboot RUN. 
#=========================#===================#==========================================================#
# check_by_git_and_reboot # 'name' 'run_path' # if git pull change, will CD to 'run_path',and run 'name' # 
# kill_runner             # 'name'            # kill -9 which has 'name'                                 #
# reboot_runner           # 'name' 'run_path' # CD to 'run_path' and run 'name'                          #
#=========================#===================#==========================================================#
def check_by_git_and_reboot(name,run_path='.'):
    with open('last_id','r') as f:
        LAST_COMMIT_ID=f.read()
    cmd='sh git_pull.sh'
    line,a=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE).communicate()
    commit_id=re.findall('commit (.*?)\s',line)[0]
    try:
        if LAST_COMMIT_ID==commit_id:
            log_set('Git not change')
        else:
            with open('last_id','w+') as f:
                f.write(commit_id)
            log_set('Git change')
            kill_runner(name)
            time.sleep(5)#if not sleep,sometimes will kill the new run.
            reboot_runner(name,run_path)
    except Exception as e:
        log_set(str(e))
        #there is network error

#kill the RUN
def kill_runner(name): 
    order = "ps x|grep %s|grep -v grep |grep -v Reboot.py |awk '{print $1}'|xargs kill -9"%'main'
    os.system(order)
    log_set('kill [%s] is ok'%name)

def reboot_runner(name,run_path='.'):
    #code = os.system('service network restart')
    code = os.system('/bin/systemctl stop  NetworkManager.service')
    code = os.system('pppoe-stop')
    code = os.system('pppoe-start')
    order = 'cd %s'%run_path
    code = os.system(order)
    if code:
        log_set('run path is unknow')
        return False
    log_set('cd %s ok'%run_path)
    order = '/root/scrapy/bin/python %s'%name
    os.system(order)
    log_set('run stop')

#def kill_self():
#    order = "ps x|grep Reboot.py|grep -v grep |awk '{print $1}'|xargs kill -9"
#    os.system(order)

if __name__ == '__main__':
    if len(sys.argv) <= 2:
        print('''CheckAndReboot [run name] [run path] [force(not must)]
run name        : is you main file name
run path        : is you run path. If '.',it meat on this path. If './abc' it meat CD to 'abc' dir.
force(not must) : if had running,you should not give. if something at here, it meat only reboot.''')
        print('For exmaple: python CheckAndReboot.py run.py . 1')
    elif len(sys.argv)==3:
        print ('check and reboot!!!')
        check_by_git_and_reboot(sys.argv[1],sys.argv[2])
    else:
        print ('force run it!!!')
        reboot_runner(sys.argv[1],sys.argv[2])

